<?php
/*
 * inc-viewSource.php
 * Retral/CSCD494 Winter 2009
 * Eastern Washington University
 *
 * File Description:
 * View the source of a file
 * Uses CSS word wrapping, but allows PHP word breaking (with <br> tags) for browsers
 * that implement this CSS in different ways (i.e. scrollbars, word wrapping, word breaking, etc)
 * 
 * Other:
 * 
 */

/* 
 * Set up $page_name
 * This name will be compared to PAGE_NAME in NAV_URLS table (stored in session) and verify permission for given user.
 */
 
$page_name = "Exams";
$page_name = strtoupper($page_name);

$pm = $_SESSION['pagePermissions'];

// Is user logged in, and has permissions?
if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] !="" && $_SESSION['pagePermissions'][$page_name] == 1)
{

?>
<link rel='stylesheet' href="css/preview.css" type="text/css" media="screen">
<link rel='stylesheet' 
<form action="<?php echo $_SERVER['PHP_SELF'] . '?page=viewSource&id=' . $_REQUEST['id'] . '&qid=' . $_REQUEST['qid'] . '&ver=' . $_REQUEST['ver']; ?>" method="POST" enctype="multipart/form-data" >
<?php
	//require('class.highlighter.php');
	$conn = oci_connect(ORA_CON_UN, ORA_CON_PW, ORA_CON_DB);
    $id = $_REQUEST['id'];
        
			// Set $minVal = 5 if not set, otherwise use current val
		if (!isset($_REQUEST['min']))
			$minVal = 5;
		else
			$minVal = $_REQUEST['min'];
			
			
	if(isset($_POST['submit']))
    {
        if($_POST['selection'] == 'delete')
        {
            $query = ' DELETE FROM source_file ' .
                     ' WHERE source_file_id = :ID ';
            
            $stmt = oci_parse($conn, $query);
            oci_bind_by_name($stmt, ':ID', $id);
            
            if(oci_execute($stmt))
                print "<p><font color='#007700'>File Successfully Deleted! </font></p><br>";
            else
                print "<p><font color='#FF0000'> Error! Could not delete the file with id: $id. Please contact an administrator. </font></p><br>";
            
        }
        else
        {
            print "<p> Please specify a new file to replace the current one. </p>";
            print "<input type='file' name='fileUpload' class='required' value=''><br><br>";
            print "<input type='submit' name='fileUploadSubmit' class='buttom' value='Upload New File'><br><br>";
        }
		
		
        echo "<a href='?page=question&id=" . $_REQUEST['qid'] . "&ver=" . $_REQUEST['ver'] . "&min=$minVal&qAproval'>Back to Edit/View Question</a><br>";
    }
    else if(isset($_POST['fileUploadSubmit']))
    {
        if(!empty($_FILES["fileUpload"]["name"]))
        {
            $query = 	" BEGIN " .
                        "    UPDATE source_file " .
                        "    SET source_file = EMPTY_BLOB() " .
                        "    WHERE source_file_id = :ID " .
                        "    RETURNING source_file INTO :sourceFile; " .
                        " END; ";
                        
            $lob_source_file = oci_new_descriptor($conn, OCI_D_LOB);   

            $stmt = oci_parse($conn, $query);
            oci_bind_by_name($stmt, ':ID', $id);
            oci_bind_by_name($stmt, ':sourceFile', $lob_source_file, -1, OCI_B_BLOB);
            oci_execute($stmt, OCI_DEFAULT);
        

            if($lob_source_file->savefile($_FILES['fileUpload']['tmp_name']))
            {
                oci_commit($conn);
                oci_free_statement($stmt);
                print "<p><font color='#00FF00'>Uploaded New File Successfully! </font></p><br><br>";
            }
            else
                 print "<p><font color='#FF0000'> Unable to upload new file! Please contact an administrator. </font></p><br>";
            print "<a href='?page=question&id=" . $_REQUEST['qid'] . "&ver=" . $_REQUEST['ver'] . "&min=$minVal&qAproval'>Back to Edit/View Question</a><br>";
        }
        else
        {
            print "<p><font color='#FF0000'> Unable to upload new file! Please make sure you specify a file. </font></p><br>";
            print "<a href='?page=viewSource&id=" . $_REQUEST['id'] . '&qid=' . $_REQUEST['qid'] . "&ver=" . $_REQUEST['ver'] . "&min=$minVal'>Try Again</a><br>";
        }
		
    }
    else
    {
        $query = '
            SELECT source_file FROM source_file
            WHERE source_file_id=:ID';



        $stmt = oci_parse($conn, $query);
        oci_bind_by_name($stmt, ':ID', $id);
        if(!oci_execute($stmt))
            print "<P>Could not query database for source file $id";

        $basicInfo = oci_fetch_assoc($stmt);
        if(!$basicInfo)
            print "<P>Could not find source $id</P>";

        oci_free_statement($stmt);

        print "<span class='header-text'>Source Code</span><br/>\n";
        print "<a href='?page=question&id=" . $_REQUEST['qid'] . "&ver=" . $_REQUEST['ver'] . "&min=$minVal&qAproval'>Back to Edit/View Question</a><br>";
        //$hl = new highlighter;
        //$hl->highlight_content($basicInfo["SOURCE_FILE"]->load());
        //print "<a href='?page=editSource&id=".$_REQUEST['id']."'> <strong> EDIT </strong></a> ";
       print '<table> <tr> <td>' .
              '<p> Action: ' .
              '<select name="selection">' .
              '<option value ="new"> Upload Different Content for this File </option>' .
              '<option value ="delete"> Delete this File </option>' . 
              '</select> &nbsp' .
              '<input type="submit" value="Go" name="submit" id="submit">' .
              '</p>' .
              '</td> </tr> </table>' ;
		if (isset($_REQUEST['name']))
			$fileNameDisplay = $_REQUEST['name'];
		else
			$fileNameDisplay = "FILE CONTENTS:";
		
		echo "<br><span style=\"color:#660000;font-size:10px;\">$fileNameDisplay&nbsp;&nbsp;&nbsp;[";
		echo "<a href=\"". $_SERVER['PHP_SELF'] . "?page=viewSource&id=" . $_REQUEST['id'] . "&qid=" . $_REQUEST['qid'] . "&ver=" . $_REQUEST['ver'] . "&name=" . $_REQUEST['name'] . "&min=$minVal&";
				if (isset($_REQUEST['nowrap']) && $_REQUEST['nowrap'] == 1)
					echo "nowrap=0\">Turn Word Wrap On</a>";
				else
					echo "nowrap=1\">Turn Word Wrap Off</a>";
		echo "]</span>";
        echo "<div style=\"width:95%; max-width:95%; min-height:1px;overflow:auto;word-wrap:break-word;border:inset 1px black;padding:5px;\"><pre>";
		if (isset($_REQUEST['nowrap']) && $_REQUEST['nowrap'] == 1)
			$codeWrapped = $basicInfo["SOURCE_FILE"]->load();
		else
			$codeWrapped = wordwrap($basicInfo["SOURCE_FILE"]->load(),90,'<br>',TRUE); //wrap number of characters. TRUE will break words if needed
			
		echo $codeWrapped . "</pre></div>";
		//echo $basicInfo["SOURCE_FILE"]->load()."</pre></div>";
        //echo($h1->output());
    }
?>
</form>
<?php
} //end if logged in
else
{
	echo "Invalid credentials";
	echo "<META http-equiv=\"refresh\" content=\"0;URL=index.php?page=login&ld=0\">";
}	
?>
